package xyz.jcat.biz.service.common;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import xyz.jcat.common.auth.UserContextHolder;
import xyz.jcat.mybatis.DBConst;

import java.util.Date;
import java.util.Objects;

/**
 * TODO
 * mybatis-plus自动填充字段值
 */
@Configuration
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        setValues(DBConst.PO_FIELD_CREATE_TIME, FieldType.DATE, metaObject, FieldFill.INSERT);
        setValues(DBConst.PO_FIELD_UPDATE_TIME, FieldType.DATE, metaObject, FieldFill.INSERT);
        setValues(DBConst.PO_FIELD_CREATOR, FieldType.USER_ID, metaObject, FieldFill.INSERT);
        setValues(DBConst.PO_FIELD_UPDATER, FieldType.USER_ID, metaObject, FieldFill.INSERT);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setValues(DBConst.PO_FIELD_UPDATE_TIME, FieldType.DATE, metaObject, FieldFill.UPDATE);
        setValues(DBConst.PO_FIELD_UPDATER, FieldType.USER_ID, metaObject, FieldFill.UPDATE);
    }

    private MetaObjectHandler setValues(String fieldName, FieldType fieldType, MetaObject metaObject, FieldFill fieldFill) {
        Object oldValue = getFieldValByName(fieldName, metaObject);
        //新增的时候如果原数据有值则不设置默认值
        if (Objects.equals(fieldFill, FieldFill.INSERT) && oldValue != null) {
            // not handle
        } else {
            setFieldValByName(fieldName, fieldType, metaObject);
        }
        return this;
    }

    public MetaObjectHandler setFieldValByName(String fieldName, FieldType fieldType, MetaObject metaObject) {
        if (metaObject.hasSetter(fieldName)) {
            switch (fieldType) {
                case DATE:
                    metaObject.setValue(fieldName, new Date());
                    break;
                case USER_ID:
                    metaObject.setValue(fieldName, UserContextHolder.getInstance().getUserId());
                    break;
            }
        }
        return this;
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        return new PaginationInnerInterceptor();
    }

    enum FieldType {
        DATE, USER_ID;
    }
}
